package com.example.video.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.video.conf.WebSecurityConfig;
import com.example.video.entity.User;
import com.example.video.conf.DBUserDetailsManager;
import com.example.video.mapper.UserMapper;
import com.example.video.service.IUserService;
import com.example.video.util.RoleUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author qiusuyang
 * @since 2024-04-13
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private DBUserDetailsManager dbuserDetailsManager;
    @Resource
    private WebSecurityConfig webSecurityConfig;
    @Override
    public void saveUserDetails(User user) {
        log.info("UserServiceImpl -> saveUserDetails ->msg: user.pwd = "+user.getUserPwd());
        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withDefaultPasswordEncoder()
                .username(user.getUserName())
                .password(user.getUserPwd())
                .roles(user.getRole())
//                .authorities(new SimpleGrantedAuthority(user.getRole()))
                .build();
        log.info("UserServiceImpl -> saveUserDetails ->msg: user.role = "+user.getRole());
        dbuserDetailsManager.createUser(userDetails);
    }

    /**
     * 更新用户详细信息。
     * 更新安全框架中的用户信息，以确保用户认证信息的一致性。
     *
     * @param user 用户对象，包含待更新的用户信息。
     * @return 如果更新成功，返回true；如果更新过程中发生异常，返回false。
     * @author ayan
     */
    @Override
    public boolean updateUserDetails(User user) {
        log.info("UserServiceImpl -> updateUserDetails ->msg: 进入修改用户 ");
        // 根据用户ID查询现有的用户信息。
        User existingUser = userMapper.selectOne(new QueryWrapper<User>().eq("id", user.getId()));
        try {
            // 更新数据库中的用户信息，以便后续查找
            existingUser.setUserName(user.getUserName());

            // 通过ID更新用户信息。
            userMapper.updateById(existingUser);
            // 根据更新后的用户信息，创建新的UserDetails对象。
            UserDetails userDetails;
            //若传入的密码为空，则使用旧密码，若不为空，则使用新密码
            if (user.getUserPwd() != null && !user.getUserPwd().isEmpty()) {
                userDetails = org.springframework.security.core.userdetails.User
                        .withDefaultPasswordEncoder()
                        .username(existingUser.getUserName())
                        .password(user.getUserPwd())
                        .roles(user.getRole())
                        .build();
            } else {
                userDetails = org.springframework.security.core.userdetails.User
                        .withUsername(existingUser.getUserName())
                        .password(existingUser.getUserPwd())
                        .roles(user.getRole())
                        .build();
            }

            // 更新安全框架中的用户信息
            dbuserDetailsManager.updateUser(userDetails);

            return true;
        } catch (Exception e) {
            // 捕获并处理更新过程中可能发生的任何异常。
            // 记录异常日志
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteUserById(Integer userId) {
        // 1. 查询要删除的用户
        User user = userMapper.selectById(userId);
        try {
            //  删除数据库中的用户记录
            int rows = userMapper.deleteById(user.getId());
            return rows > 0;
        } catch (Exception e) {
            // 记录异常日志
            e.printStackTrace();
            throw new RuntimeException("删除用户失败：" + e.getMessage());
        }
    }
    @Override
    public User getById(Integer id){
        return userMapper.selectOne(new QueryWrapper<User>().eq("id",id)
                .select("id","user_name","role","group_id")
        );
    }

    @Override
    public boolean login(String username, String password) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_name",username));
        if(user == null ){
            return false;
        }else{
            if(user.getUserPwd().equals(password)){
                return true;
            }else{
                return false;
            }
        }
    }
    @Override
    public List<User> getList(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        // 获取用户的所有权限
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        // 提取并格式化角色
        List<String> formattedRoles = RoleUtils.extractAndFormatRoles(authorities);

        // 根据用户角色，返回对应的数据
        QueryWrapper<User> qwrapper = new QueryWrapper<>();
        // 如果formattedRoles中包含[[ROLE_ADMIN]]，则返回表中所有数据
        if (formattedRoles.size() == 1 && formattedRoles.get(0).equals("[ROLE_ADMIN]")) {
            // 不设置任何角色条件，返回所有用户数据
        } else {
            // 设置查询条件，匹配formattedRoles列表中的任一角色
            if (!formattedRoles.isEmpty()) {
                qwrapper.in("role", formattedRoles);
            }
        }

        return userMapper.selectList(qwrapper);
    }
    @Override
    public List<User> getAllRoles() {
        // 从数据库查询所有用户记录
        List<User> allUsers = userMapper.selectList(null);

        // 去除重复的role字段，创建新的List<User>
        List<User> uniqueRoles = allUsers.stream()
                .map(User::getRole) // 提取每个用户的role字段
                .distinct() // 去除重复的role
                .map(role -> {
                    User user = new User();
                    user.setRole(role);
                    return user;
                })
                .collect(Collectors.toList());
        return uniqueRoles;
    }
    @Override
    public User getByName(String username) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("user_name",username));
    }


    @Override
    public void addItem(User user) {
        userMapper.insert(user);
    }

    @Override
    public boolean updateItem(User user) {
        return userMapper.updateById(user) > 0;
    }

    @Override
    public List<User> getListByRole(Integer page, Integer limit, String role) {
        QueryWrapper<User> qwrapper = new QueryWrapper<>();
        qwrapper.select("id","user_name","group_id","role");
        if(role != null && !"".equals(role)){
            qwrapper.eq("role","[ROLE_"+role+"]");
        }
        IPage<User> ipage = userMapper.selectPage(new Page<>(page, limit), qwrapper);
        return ipage.getRecords();
    }

    // TODO 删除用户
    @Override
    public boolean deleteByUserId(Integer userId) {

        return true;
    }
}
